package com.gzqylc.docker.extend.exception;

import com.alibaba.fastjson.JSONObject;
import com.gzqylc.framework.AjaxResult;
import com.gzqylc.framework.GlobalExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class ExtendGlobalExceptionHandler extends GlobalExceptionHandler {


    public static final String BUSINESS_CODE = "BusinessCode";


    private void storeException(HttpServletRequest request, Throwable e) {
        request.setAttribute(EXCEPTION_KEY, e);
    }

    private void setBusinessCode(HttpServletRequest request, String businessCode){
        request.setAttribute(BUSINESS_CODE,businessCode);
    }

    @ExceptionHandler(ApiBusinessException.class)
    public AjaxResult ApiBusinessException(ApiBusinessException e, HttpServletRequest request) {
        log.error("接口业务异常，原因:{},目标:{}", e.getMessage(), JSONObject.toJSONString(e.getTarget()));
        e.printStackTrace();
        this.storeException(request, e);
        this.setBusinessCode(request,e.getBusinessExceptionEnums().getBusinessCode());
        AjaxResult result = AjaxResult.error(e.getMessage());
        result.put("businessCode",e.getBusinessExceptionEnums().getBusinessCode());
        return result;
    }

    /**
     * 拦截@RequestParam 参数为空的异常
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public AjaxResult runtimeException(MissingServletRequestParameterException e, HttpServletRequest request) {
        String errorMessage = e.getParameterName() + "不能为空";
        log.error("缺少参数:{}", errorMessage);
        this.storeException(request, e);
        return AjaxResult.error(errorMessage);
    }
}
